<template>
  <div id="app" style="max-width: 750px;margin:0 auto;">

    <van-sticky >

        <van-search v-if="pathName=='home'"
                v-model="keyword"
                show-action
                style="max-width: 750px;margin:0 auto;"
                placeholder="支持多个关键词空格隔开搜索，如:领导 发言"
                @search="search"
        >
          <template #action>
            <div @click="search">搜索</div>
          </template>
        </van-search>
    </van-sticky>
    <div class="container">
      <keep-alive>
        <router-view v-if="$route.meta.keepAlive"></router-view>
      </keep-alive>
      <router-view v-if="!$route.meta.keepAlive"></router-view>
      <div style="height: 60px;"></div>
      <van-tabbar v-if="pathName!='detail'" active-color="#1AA97B"  @change="tabBarChange" :safe-area-inset-bottom="true" v-model="active">
        <van-tabbar-item to="/" icon="wap-home">
          <template #icon>
            <i class="fas fa-home"></i>
          </template>
          平台首页
        </van-tabbar-item>
        <van-tabbar-item to="/channel" icon="todo-list">
          <template #icon>
            <i class="fas fa-clipboard-list"></i>
          </template>
          全部分类
        </van-tabbar-item>
        <van-tabbar-item to="/search" icon="search">
          <template #icon>
            <i class="fas fa-search"></i>
          </template>
          搜索资料
        </van-tabbar-item>
        <van-tabbar-item to="/vip" >
          <template #icon>
            <i class="fas fa-crown"></i>
          </template>
          开通会员
        </van-tabbar-item>
      </van-tabbar>
    </div>
    <RightMenu v-if="pathName!='home'"></RightMenu>
  </div>
</template>

<script>
  import RightMenu from "@/components/RightMenu.vue";
  import Login from "@/components/Login.vue";
  import wx from "weixin-js-sdk";
  export default {
    name: "homeview",
    components:{
      RightMenu,
    },
    data() {
      return {
        classifies:[],
        hotWords:[],
        pathName:'',
        keyword:'',
        showLogin:false,
        active:0,
        channelListVisible:false,
        pid:'',

      };
    },
    created(){
      let code=this.$utils.getQueryVariable('code');
      this.pid=this.$utils.getQueryVariable('pid');

      if(code){
        //登录
        this.$apis.wechatLogin({code: code,pid:this.pid}).then(res => {
          if(res.records&&Object.keys(res.records).length>0){
            this.$store.dispatch('user/updateUserInfo', res.records)
            this.$store.dispatch('user/updateToken', res.records.token)
            // console.log(this.$store.getters.userInfo)
            // let curUrl=this.$utils.removeQueryParam(window.location.href,'code')
            // curUrl=this.$utils.removeQueryParam(curUrl,'stae')
            // window.location.href=curUrl;
          }
        })
      }else{
        let redirect_uri=encodeURIComponent(window.location.href)
        let wechatLoginUrl= `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.$config.wechatAppId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
        if(this.$config.verifyWechatLogin==1){
          window.location.href=wechatLoginUrl;
        }
        if(this.$store.getters.token){
          this.getUserInfo()
        }
        // if(!this.$store.getters.token){
        //   if(this.$config.verifyWechatLogin==1){
        //     window.location.href=wechatLoginUrl;
        //   }
        // }else{
        //   this.getUserInfo()
        // }
      }

      this.$watch(
              () => this.$route.params,
              () => {
                this.pathName=this.$route.name;
                this.setTabBar();
                if(this.pathName!='search'||this.pathName!='detail'){
                  setTimeout( ()=> {
                    if(this.$store.getters.token){
                      this.wxShareInit();
                    }

                  },1000)
                }



              },
              // 组件创建完后获取数据，
              // 此时 data 已经被 observed 了
              { immediate: true }
      )

      this.$apis.homeData().then(res=>{
        this.classifies=res.classifies;
        this.hotWords=res.hotWords;
      })
    },


    mounted:function(){
      this.$router.onReady(() => {
        let query=this.$route.query;
        if(query.code){
          query=JSON.parse(JSON.stringify(query));
          delete query.code;
          delete query.state;
          // window.history.replaceState(query,null,this.$route.path);
          //修改地址栏参数，防止刷新后
          this.$router.replace({path:this.$route.path,query:query})
        }
      });
      this.$nextTick(()=>{

      })
    },
    methods: {
      setTabBar(){
        if(this.pathName=='home'){
          this.active=0;
        }else if(this.pathName=='channel'){
          this.active=1;
        }else if(this.pathName=='search'){
          this.active=2;
        }else if(this.pathName=='vip'){
          this.active=3;
        }else if(this.pathName=='list'){
          this.active=null;
        }
      },
      wxShareInit(){
        let title=document.title;
        console.log(title);
        if(!title){
          title="池塘边素材网";
        }
        let curUrl=this.$utils.removeQueryParam(window.location.href,'pid');
        if(this.$store.getters.userInfo){
          curUrl=curUrl+"?pid="+this.$store.getters.userInfo.union_id;
        }
        let shareUrl=curUrl

        let params={
          url:shareUrl
        }
        this.$apis.wxConfig(params).then(res => {
          let wxConfig=JSON.parse(res.records.wxConfig);
          let icon=this.$config.host+'/static/images/logo.jpg';
          wx.config({
            debug: false, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来，若要查看传入的参数，可以在 pc 端打开，参数信息会通过 log 打出，仅在 pc 端时才会打印。
            appId: wxConfig.appId, // 必填，公众号的唯一标识
            timestamp:wxConfig.timestamp, // 必填，生成签名的时间戳
            nonceStr: wxConfig.nonceStr, // 必填，生成签名的随机串
            signature: wxConfig.signature,// 必填，签名
            jsApiList:wxConfig.jsApiList // 必填，需要使用的 JS 接口列表
          });

          wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
            wx.updateAppMessageShareData({
              title:title, // 分享标题
              //desc: info.title, // 分享描述
              desc: "扣时事，跟热点，日更新", // 分享描述
              link: shareUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
              imgUrl: icon, // 分享图标
              success: function () {
                // 设置成功
              }
            })
            wx.updateTimelineShareData({
              title:title, // 分享标题
              link: shareUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
              imgUrl: icon, // 分享图标
              success: function () {
                // 设置成功
              }
            })

            wx.onMenuShareWeibo({
              title: title, // 分享标题
              //desc: info.title, // 分享描述
              desc: "扣时事，跟热点，日更新",
              link: shareUrl, // 分享链接
              imgUrl: icon, // 分享图标
              success: function () {
                // 用户确认分享后执行的回调函数
              },
              cancel: function () {
                // 用户取消分享后执行的回调函数
              }
            });
            wx.onMenuShareQQ({
              title: title, // 分享标题
              desc: "扣时事，跟热点，日更新",
              //desc: info.title, // 分享描述
              link: shareUrl, // 分享链接
              imgUrl: icon, // 分享图标
              success: function () {
                // 用户确认分享后执行的回调函数
              },
              cancel: function () {
                // 用户取消分享后执行的回调函数
              }
            });

          });
        })
      },
      tabBarChange(index){
        // if(index==1){
        //   this.channelListVisible=true;
        // }
      },
      exitLogin(){
        this.$store.dispatch('user/updateUserInfo', null)
        this.$store.dispatch('user/updateToken', null)
      },
      getUserInfo(){
        this.$apis.userInfo({}).then(res=>{
          let userInfo=res.records;
          this.$store.dispatch('user/updateUserInfo', userInfo)
          // this.$store.dispatch('user/updateToken', token)
        })
      },
      search(){
        if(!this.keyword){
          this.$toast('请输入搜索关键词');
          return;
        }
        this.$router.push({ path: `/search/${this.keyword}` })

      }
    }
  }
</script>
<style lang="less">

</style>
